/**
 *       Copyright (c) 2012 Lukas Zaruba
 *
 *   This file is part of Robot Playground.
 *
 *   Robot Playground is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   Robot Playground is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public License
 *   along with Robot Playground. If not, see <http://www.gnu.org/licenses/>.
 */
package net.zarubsys.commons.scripting.functions.internal;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import net.zarubsys.commons.scripting.IScriptFunction;
import net.zarubsys.commons.scripting.ParsedStatement;
import net.zarubsys.commons.scripting.ScriptingEnvironment;
import net.zarubsys.commons.scripting.ScriptingException;
import net.zarubsys.commons.scripting.variables.IVariablePool;

import org.apache.log4j.Level;

/**
 * Based on scripting language from Media Solutions Slovakia, a.s.
 * @author Lukas Zaruba, lukas.zaruba@gmail.com
 */
public class DumpFunction implements IScriptFunction {
	
	@Override
	public String getName() {
		return "dump";
	}
	
	@Override
	public int getMinArgsNum() {
		return 0;
	}
	
	@Override
	public int getMaxArgsNum() {
		return 0;
	}
	
	private static void dumpValues(StringBuilder sb, IVariablePool pool) throws ScriptingException {
		List<String> propList = new ArrayList<String>(pool.getPropertyList());
		Collections.sort(propList);
		for (String prop : propList) {
			Object value = pool.getProperty(prop);
			sb.append("[" + pool.getPoolName() + "]:" + prop + " = " + getStringRepresentation(value)).append("\n");			
		}
	}
	
	private static Object getStringRepresentation(Object value) {
		if (value == null) {
			return "[null]";
		}
		try {
			return value.toString();
		} catch (Exception e) {
			return "<" + e.getClass().getName() + " : " + e.getMessage() + ">";
		}
	}

	@Override
	public Object execute(ScriptingEnvironment env, List<ParsedStatement> args) throws ScriptingException {
		Map<String, IVariablePool> allPools = env.getAllPools();
        StringBuilder sb = new StringBuilder();
		sb.append("\n\n");
		sb.append("\"DUMP\" - all defined properties at this point (").append(env.getCurrentScriptLocator().getLocation()).append("):");
		sb.append("\n");
		for (IVariablePool varPool : allPools.values()) {
			dumpValues(sb, varPool);
		}
        sb.append("\n");
        sb.append("---------------");
        env.getScriptLog().log(Level.INFO, sb.toString());
        return null;
    }

}
